package jwei.apps.indextank.providers;

import java.util.HashMap;

import jwei.apps.indextank.db.IngredientCache.IngredientsCache;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class IngredientsContentProvider extends ContentProvider {

    private static final String TAG = "IngredientsContentProvider";

    private static final String DATABASE_NAME = "ingredients_cache.db";

    private static final int DATABASE_VERSION = 1;

    private static final String INGREDIENTS_TABLE_NAME = "ingredients_cache";

    public static final String AUTHORITY = "jwei.apps.indextank.providers.IngredientsContentProvider";

    private static final UriMatcher sUriMatcher;

    private static final int INGREDIENTS = 1;

    private static final int INGREDIENTS_ID = 2;

    private static HashMap<String, String> projectionMap;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + INGREDIENTS_TABLE_NAME + " (" + IngredientsCache._ID
                    + " INTEGER PRIMARY KEY AUTOINCREMENT," + IngredientsCache.NAME + " VARCHAR(255)" + " );");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
                    + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + INGREDIENTS_TABLE_NAME);
            onCreate(db);
        }
    }

    private DatabaseHelper dbHelper;

    /*
     * (non-Javadoc)
     * 
     * @see android.content.ContentProvider#delete(android.net.Uri,
     * java.lang.String, java.lang.String[])
     */
    @Override
    public int delete(Uri uri, String where, String[] whereArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
            case INGREDIENTS:
                count = db.delete(INGREDIENTS_TABLE_NAME, where, whereArgs);
                break;
            case INGREDIENTS_ID:
                String productId = uri.getPathSegments().get(1);
                count = db.delete(INGREDIENTS_TABLE_NAME, IngredientsCache._ID + "=" + productId
                        + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.content.ContentProvider#getType(android.net.Uri)
     */
    @Override
    public String getType(Uri uri) {
        switch (sUriMatcher.match(uri)) {
            case INGREDIENTS:
                return IngredientsCache.CONTENT_TYPE;
            case INGREDIENTS_ID:
                return IngredientsCache.CONTENT_ITEM_TYPE;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.content.ContentProvider#insert(android.net.Uri,
     * android.content.ContentValues)
     */
    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {
        if (sUriMatcher.match(uri) != INGREDIENTS) { throw new IllegalArgumentException("Unknown URI " + uri); }

        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        long rowId = db.insert(INGREDIENTS_TABLE_NAME, IngredientsCache.INGREDIENTS, values);
        if (rowId > 0) {
            Uri noteUri = ContentUris.withAppendedId(IngredientsCache.CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.content.ContentProvider#onCreate()
     */
    @Override
    public boolean onCreate() {
        dbHelper = new DatabaseHelper(getContext());
        return true;
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.content.ContentProvider#query(android.net.Uri,
     * java.lang.String[], java.lang.String, java.lang.String[],
     * java.lang.String)
     */
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

        switch (sUriMatcher.match(uri)) {
            case INGREDIENTS:
                qb.setTables(INGREDIENTS_TABLE_NAME);
                qb.setProjectionMap(projectionMap);
                break;
            case INGREDIENTS_ID:
                qb.setTables(INGREDIENTS_TABLE_NAME);
                qb.setProjectionMap(projectionMap);
                qb.appendWhere(IngredientsCache._ID + "=" + uri.getPathSegments().get(1));
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);

        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.content.ContentProvider#update(android.net.Uri,
     * android.content.ContentValues, java.lang.String, java.lang.String[])
     */
    @Override
    public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
            case INGREDIENTS:
                count = db.update(INGREDIENTS_TABLE_NAME, values, where, whereArgs);
                break;
            case INGREDIENTS_ID:
                String sermonId = uri.getPathSegments().get(1);
                count = db.update(INGREDIENTS_TABLE_NAME, values, IngredientsCache._ID + "=" + sermonId
                        + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(AUTHORITY, INGREDIENTS_TABLE_NAME, INGREDIENTS);
        sUriMatcher.addURI(AUTHORITY, INGREDIENTS_TABLE_NAME + "/#", INGREDIENTS_ID);

        projectionMap = new HashMap<String, String>();
        projectionMap.put(IngredientsCache._ID, IngredientsCache._ID);
        projectionMap.put(IngredientsCache.NAME, IngredientsCache.NAME);
    }
}
